# 最小操作系统构建脚本 - 实验七：文件系统

# 工具链设置
CROSS_COMPILE = riscv64-unknown-elf-
CC = $(CROSS_COMPILE)gcc
AS = $(CROSS_COMPILE)as
LD = $(CROSS_COMPILE)ld
OBJCOPY = $(CROSS_COMPILE)objcopy
OBJDUMP = $(CROSS_COMPILE)objdump
NM = $(CROSS_COMPILE)nm

# 编译选项
CFLAGS = -Wall -Werror -O -fno-omit-frame-pointer -ggdb
CFLAGS += -MD
CFLAGS += -mcmodel=medany
CFLAGS += -ffreestanding -fno-common -nostdlib -mno-relax
CFLAGS += -I. -Ifs
CFLAGS += -fno-builtin

# 链接选项
LDFLAGS = -z max-page-size=4096

# 目标文件列表 - 添加 kalloc.o 和 vm.o
OBJS = \
  boot/entry.o \
  start.o \
  main.o \
  uart.o \
  string.o \
  printf.o \
  console.o \
  kalloc.o \
  vm.o \
  spinlock.o \
  trap.o \
  kernelvec.o \
  timervec.o \
  exception.o \
  proc.o \
  swtch.o \
  proc_tests.o \
  syscall.o \
  sysproc.o \
  sysfile.o \
  syscall_tests.o \
  fs/sleeplock.o \
  fs/virtio_disk.o \
  fs/ramdisk.o \
  fs/bio.o \
  fs/log.o \
  fs/fs.o \
  fs/file.o \
  fs/fs.tests.o

# 主要目标
kernel: $(OBJS) kernel.ld
	$(LD) $(LDFLAGS) -T kernel.ld -o kernel $(OBJS)
	$(OBJDUMP) -S kernel > kernel.asm
	$(OBJDUMP) -t kernel | sed '1,/SYMBOL TABLE/d; s/ .* / /; /^$$/d' > kernel.sym

# 汇编文件编译规则
boot/entry.o: boot/entry.S
	$(CC) $(CFLAGS) -c $< -o $@

%.o: %.S
	$(CC) $(CFLAGS) -c $< -o $@

# C文件编译规则
%.o: %.c
	$(CC) $(CFLAGS) -c $< -o $@

# 包含依赖文件
-include *.d boot/*.d fs/*.d

# 清理目标
clean:
	rm -f *.o boot/*.o fs/*.o kernel kernel.asm kernel.sym *.d boot/*.d fs/*.d

# QEMU运行
qemu: kernel
	qemu-system-riscv64 -machine virt -bios none -kernel kernel -nographic

# QEMU调试模式
qemu-gdb: kernel
	qemu-system-riscv64 -machine virt -bios none -kernel kernel -nographic -gdb tcp::1234 -S

# printf功能测试
test-printf: kernel
	@echo "=== Running printf functionality test ==="
	qemu-system-riscv64 -machine virt -bios none -kernel kernel -nographic

# 伪目标声明
.PHONY: clean qemu qemu-gdb test-printf